package com.chinaoly.baotou.common.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @description 使用RestTemplate进行三方接口交互工具类
 * Create by sunlm
 * on 2023-05-08 11:08
 * Make small but daily progress
 */
public class TemplateUtil {

    /**
     * @description: 请求三方POST接口，postJsonBody(@RequestBody String data)
     * @author: sunlm
     * @date: 2023/5/8 14:42
     * @param: [restTemplate, url, json]
     * @return: java.lang.String
     **/
    public static ResponseEntity<String> postForBodyJson(RestTemplate restTemplate, String url, String json) {
        // 构建消息头
        HttpHeaders headers = new HttpHeaders();
        // 设置请求头内容类型Content-Type为："application/json"，编码格式为："UTF-8"
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        // 构建消息体
        HttpEntity<String> request = new HttpEntity<>(json, headers);
        // 向服务端发送请求
        return restTemplate.postForEntity(url, request, String.class);
    }

    /**
     * @description: 请求三方POST接口，postJsonParam(@RequestParam String data)
     * @author: sunlm
     * @date: 2023/5/8 14:43
     * @param: [restTemplate, url, json]
     * @return: java.lang.String
     **/
    public static ResponseEntity<String> postForParamJson(RestTemplate restTemplate, String url, String json) {
        // 构建消息头
        HttpHeaders requestHeaders = new HttpHeaders();
        // 设置请求头内容类型Content-Type
        requestHeaders.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        // 构建消息体内容
        MultiValueMap requestBody = new LinkedMultiValueMap();
        requestBody.add("data",json);
        // 完整的消息体
        HttpEntity<MultiValueMap> entity = new HttpEntity<>(requestBody, requestHeaders);
        // 向服务端发送请求
        return restTemplate.postForEntity(url, entity, String.class);
    }
}
